Getting the Picture II

In this recipe we use image arrays to cache cels for smoother animation.

 

Discussion

(It's typical to refer to a single image in an animation as a frame. Because HTML also supports frames, we've chosen the word cel instead, to avoid confusion.)

The only image loaded through HTML (besides the utensil graphic at the top) is ../GRAFX/BLANK.GIF, which just serves as a placeholder for the animation. The animation cels are loaded into a JavaScript array of Image objects. Another 8-place array (which we call an animation sequencer array) holds the index of the cel to be displayed during the cycle; that way we can re-use cel graphics. This eight-cel cycle only needs five actual images.

The Setup() function is worth a deeper look. In it we load the graphics to be used in the animation.

function Setup()
{
	celArray = new Array(5);
	for(var i = 0; i < 5; i++) {
		var fName = "../GRAFX/ANIM/DOGFRM"+(i+1)+".JPG";
		celArray[i] = new Image(135,135);
		celArray[i].src = fName;
	}
	Startup();
}
The first step is to create an array to hold the images. Following that, we loop 5 times to create an Image object to hold each animation cel. The objects created in this array are not accessible through the standard HTML document.images[] array--they exist entirely within a cache maintained by the JavaScript engine. Once we've created a cel, we point it to the source of the image it should cache. Once the loop completes, we call a function to start the repeat timer.

The repeat timer calls the NextCel() function, shown below.

function NextCel()
{
	// Determine which cel displays next
	var idx = animCelNbr[celIndex++];
	document.images.animationCel.src = celArray[idx].src;
	if(celIndex >= animCelNbr.length)
		celIndex = 0;
}
The first thing this function does is determine which element of the animation sequencer array contains the cel number that's next to display; the next line assigns the source of the image created in HTML to the source of one of the cel caches. For clarity, the HTML image is named rather than referred to by its index value in the images array; we've found that it's easy to miscount the images in an HTML document while trying to determine the index of a particular image. In our first draft of this recipe we forgot about the recipe title, and were animating document.images[0], which is the picture of the knife and fork at the top of the page! Needless to say, it wasn't a very convincing demonstration, and led to our naming the graphic we intended to be animated as animationCel.


Yes, the dog has a tail. It's behind him all the time!


Copyright ©1998 by Charles River Media, All Rights Reserved